﻿using Aliphant.Common.Interfaces;
using Aliphant.Common.Tools;

namespace Aliphant.Common.Services
{
    public class CoroutineService : Singleton<CoroutineService>, IService
    {
        private Thread? _coroutineThread;
        private CancellationTokenSource? cts;

        public void Init()
        {
            _coroutineThread = new Thread(() =>
            {
                if (cts == null) return;
                while (!cts.IsCancellationRequested)
                {
                    Time.Tick();
                    CoroutineManager.Instance.Run();
                }
            });
        }

        public void Start()
        {
            cts = new CancellationTokenSource();
            _coroutineThread?.Start();
        }

        public void Stop()
        {
            cts?.Cancel();
        }

        public void ReStart()
        {
            Stop();
            Init();
            Start();
        }

        public void Release()
        {
            Stop();
            if (_coroutineThread != null && _coroutineThread.IsAlive)
            {
                _coroutineThread = null;
            }
        }
    }
}
